package com.liu.common.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.liu.common.content.RedisKeyInterface;
import com.liu.common.entity.qo.DeepSeekChatCompletionsQO;
import com.liu.common.entity.vo.DeepSeekChatCompletionsVO;
import com.liu.common.entity.vo.DeepSeekUserBalanceVO;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class DeepSeekClientUtils {

    private static final String BASE_URL = "https://api.deepseek.com";

    private static String apiKey = "";

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @PostConstruct
    public void init() {
        System.out.println("\n从redis中获取DeepSeek的apiKey");
        String uuid = redisTemplate.opsForValue().get(RedisKeyInterface.DEEPSEEK_APIKEY_ENCRYPTION_UUID_REDIS_KEY);
        if (uuid != null) {
            DES des = SecureUtil.des(uuid.getBytes());
            String encryptHex = redisTemplate.opsForValue().get(RedisKeyInterface.DEEPSEEK_APIKEY_ENCRYPTION_ENCRYPTHEX_REDIS_KEY);
            apiKey = des.decryptStr(encryptHex);
        }
    }

    /**
     * 查询账号余额
     * @return DeepSeekUserBalanceVO
     */
    public static DeepSeekUserBalanceVO getUserBalance() {
        String body = HttpRequest.get(BASE_URL + "/user/balance")
                .timeout(60000)
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                .header(Header.CONTENT_TYPE, "application/json")
                .execute()
                .body();
        return JSONUtil.parseObj(body).toBean(DeepSeekUserBalanceVO.class);
    }

    /**
     * 对话补全
     * @return DeepSeekUserBalanceVO
     */
    public static DeepSeekChatCompletionsVO getChatCompletions(DeepSeekChatCompletionsQO deepSeekChatCompletionsQO) {
        String body = HttpRequest.post(BASE_URL + "/chat/completions")
                .body(JSONUtil.toJsonStr(deepSeekChatCompletionsQO))
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                .header(Header.CONTENT_TYPE, "application/json")
                .execute()
                .body();
        return JSONUtil.parseObj(body).toBean(DeepSeekChatCompletionsVO.class);
    }
}
